﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using UCNKompetenceBors.Database;
using UCNKompetenceBors.Model;

namespace UCNKompetenceBors.Admin
{
    public partial class adminDepartmentEdit : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindSubMenu();
                BindData(Convert.ToInt32(Request.QueryString["depid"]));

                lblConfirmUpdatedDepartment.Visible = false;

                #region Globalization
                string culture = String.Empty;

                if (HttpContext.Current.Session["MyCulture"] != null)
                    culture = HttpContext.Current.Session["MyCulture"].ToString();

                if (!String.IsNullOrEmpty(culture))
                    GeneralTools.SetCulture(culture);

                LocalizeControls();
                #endregion
            }
        }

        /// <summary>
        /// Binds the sub menu links.
        /// </summary>
        private void BindSubMenu()
        {
            hyLinkAdminDashboard.NavigateUrl = "~/Admin/admin.aspx";
            hyLinkUserHandling.NavigateUrl = "~/Admin/adminUsers.aspx";
            hyLinkAdminExchange.NavigateUrl = "~/Admin/adminExchange.aspx";
            hyLinkNewsHandling.NavigateUrl = "~/Admin/adminNews.aspx";
            hyLinkEditInformation.NavigateUrl = "~/Admin/adminInformation.aspx";
            hyLinkResetUsers.NavigateUrl = "~/Admin/adminUsersReset.aspx";
            hylinkDepartment.NavigateUrl = "~/Admin/adminDepartment.aspx";
            hylinkDepartmentCreate.NavigateUrl = "~/Admin/adminDepartmentCreate.aspx";
        }

        /// <summary>
        /// Binds the controls with a department based on the departmentId parameter.
        /// </summary>
        /// <param name="departmentId">Specifies the ID of the department to be used.</param>
        private void BindData(int departmentId)
        {
            Department department = dbAdmin.GetDepartmentById(departmentId);

            txtEditDepartmentName.Text = department.Name;
            txtEditDepartmentAddress.Text = department.Address;
            txtEditDepartmentZipCode.Text = department.ZipCode;
            txtEditDepartmentCity.Text = department.City;
            txtEditDepartmentEmail.Text = department.Email;
            txtEditDepartmentPhone.Text = department.Phone;
            txtEditDepartmentFax.Text = department.Fax;

            imgEditDepartmentImage.ImageUrl = department.ImageURL;
        }

        /// <summary>
        /// Edits a department, based on the departmentId parameter.
        /// </summary>
        /// <param name="departmentId">Specifies the ID of the department to be used.</param>
        /// <param name="name">Specifies the department name to be used.</param>
        /// <param name="hasImage">Specifies whether or not contact person has an image.</param>
        /// <param name="imagePath">Specifies the path to the image</param>
        /// <param name="imageFileName">Specifies the file name of the image to be used.</param>
        /// <param name="address">Specifies the address to be used.</param>
        /// <param name="zipCode">Specifies the zip code to be used.</param>
        /// <param name="city">Specifies the city to be used.</param>
        /// <param name="email">Specifies the email to be used in the contact person.</param>
        /// <param name="phone">Specifies the phone to be used in the contact person.</param>
        /// <param name="fax">Specifies the fax to be used.</param>
        public void EditDepartment(int departmentId, string name, bool hasImage, string imageFileName, string address, string zipCode, string city, string email, string phone, string fax)
        {
            string path = "";

            //Checks whether or not an image has been selected in the fileupload control
            if (hasImage)
            {
                //Checks whether or not current image is the default image
                if (!imgEditDepartmentImage.ImageUrl.Equals("~/Images/ContactPersons/defaultCp.jpg"))
                {
                    //If the current image is not the default image, the old image is deleted
                    DeleteImage(Convert.ToInt32(Request.QueryString["nid"]), imgEditDepartmentImage.ImageUrl);
                    path = Path.GetDirectoryName(imgEditDepartmentImage.ImageUrl);
                }
                else
                {
                    path = Path.GetDirectoryName("~/Images/ContactPersons/" + txtEditDepartmentName.Text.Trim() + "/");
                }

                UploadPicture();
            }

            dbAdmin.EditDepartment(departmentId, name, hasImage, path, imageFileName, address, zipCode, city, email, phone, fax);
        }

        /// <summary>
        /// Upload an image.
        /// </summary>
        private void UploadPicture()
        {
            string path = Server.MapPath("~/Images/Departments/" + txtEditDepartmentName.Text.Replace(" ", "") + "/");
            if (!Directory.Exists(path))
            {
                DirectoryInfo dir = new DirectoryInfo(path);

                dir.Create();
            }

            if (fuEditDepartmentImage.HasFile)
            {
                System.Drawing.Image image = System.Drawing.Image.FromStream(fuEditDepartmentImage.FileContent);
                string imagePath = path + fuEditDepartmentImage.FileName;

                GeneralTools.CreateThumbnail(100, image, imagePath);
            }
        }

        /// <summary>
        /// Checks whether or not a depatment has an image, based on the departmentId parameter.
        /// </summary>
        /// <param name="departmentId">Specifies the ID of the depatment to be used.</param>
        /// <returns>Returns a boolean, specifying whether or not a depatment has an image.</returns>
        private bool HasImage(int departmentId)
        {
            return dbAdmin.DepartmentHasImage(departmentId);
        }

        /// <summary>
        /// Deletes an image, based on the departmentId and imagePath parameters.
        /// </summary>
        /// <param name="departmentId">Specifies the ID of the department to be used.</param>
        /// <param name="imagePath">Specifies the path of the image to be deleted</param>
        private void DeleteImage(int departmentId, string imagePath)
        {
            if (HasImage(departmentId))
            {
                string filePath = HttpContext.Current.Server.MapPath(imagePath);

                //Removes the filename from the path
                string path = Path.GetDirectoryName(filePath);

                File.Delete(filePath);
            }
        }

        protected void btnEditDepartment_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                lblConfirmUpdatedDepartment.Visible = true;
                int departmentId = Convert.ToInt32(Request.QueryString["depid"]);
                string name = txtEditDepartmentName.Text;
                string address = txtEditDepartmentAddress.Text;
                bool hasImage = fuEditDepartmentImage.HasFile;
                string imageFileName = fuEditDepartmentImage.FileName;
                string zipCode = txtEditDepartmentZipCode.Text;
                string city = txtEditDepartmentCity.Text;
                string email = txtEditDepartmentEmail.Text;
                string phone = txtEditDepartmentPhone.Text;
                string fax = txtEditDepartmentFax.Text;

                EditDepartment(departmentId, name, hasImage, imageFileName, address, zipCode, city, email, phone, fax);

                BindData(departmentId);
            }
        }

        /// <summary>
        /// Localizes the controls of the site, based on the current UI Culture.
        /// </summary>
        private void LocalizeControls()
        {
            hyLinkAdminDashboard.Text = GetLocalResourceObject("hyLinkAdminDashboardText").ToString();
            hyLinkUserHandling.Text = GetLocalResourceObject("hyLinkUserHandlingText").ToString();
            hyLinkAdminExchange.Text = GetLocalResourceObject("hyLinkAdminExchangeText").ToString();
            hyLinkNewsHandling.Text = GetLocalResourceObject("hyLinkNewsHandlingText").ToString();
            hyLinkEditInformation.Text = GetLocalResourceObject("hyLinkEditInformationText").ToString();
            hyLinkResetUsers.Text = GetLocalResourceObject("hyLinkResetUsersText").ToString();
            hylinkDepartmentCreate.Text = GetLocalResourceObject("hylinkDepartmentCreateText").ToString();
            hylinkDepartment.Text = GetLocalResourceObject("hylinkDepartmentText").ToString();

            lblAdminContentHeader.Text = GetLocalResourceObject("lblAdminContentHeaderText").ToString();
            lblConfirmUpdatedDepartment.Text = GetLocalResourceObject("lblConfirmUpdatedDepartmentText").ToString();
            lblEditDepartmentName.Text = GetLocalResourceObject("lblEditDepartmentName").ToString();
            lblEditDepartmentAddress.Text = GetLocalResourceObject("lblEditDepartmentAddressText").ToString();
            lblEditDepartmentZipCity.Text = GetLocalResourceObject("lblEditDepartmentZipCityText").ToString();
            lblEditDepartmentEmail.Text = GetLocalResourceObject("lblEditDepartmentEmailText").ToString();
            lblEditDepartmentPhone.Text = GetLocalResourceObject("lblEditDepartmentPhoneText").ToString();
            lblEditDepartmentFax.Text = GetLocalResourceObject("lblEditDepartmentFaxText").ToString();
            lblEditDepartmentImage.Text = GetLocalResourceObject("lblEditDepartmentImageText").ToString();

            btnEditDepartment.Text = GetLocalResourceObject("btnEditDepartmentText").ToString();
            btnCancelEditDepartment.Text = GetLocalResourceObject("btnCancelEditDepartmentText").ToString();

            string imageRegexValidaton = GetLocalResourceObject("regexvalImageText").ToString();
            regexvalImage.ToolTip = imageRegexValidaton;
            regexvalImage.ErrorMessage = imageRegexValidaton;

            string phoneValidation = GetLocalResourceObject("rfvalPhoneText").ToString();
            rfvalPhone.ToolTip = phoneValidation;
            rfvalPhone.ErrorMessage = phoneValidation;

            string phoneRegexValidation = GetLocalResourceObject("regexvalPhoneText").ToString();
            regexvalPhone.ToolTip = phoneRegexValidation;
            regexvalPhone.ErrorMessage = phoneRegexValidation;

            string faxRegexValidation = GetLocalResourceObject("regexvalFaxText").ToString();
            regexvalFax.ToolTip = faxRegexValidation;
            regexvalFax.ErrorMessage = faxRegexValidation;

            string EmailRegexValidation = GetLocalResourceObject("regexvalEmailText").ToString();
            regexvalEmail.ToolTip = EmailRegexValidation;
            regexvalEmail.ErrorMessage = EmailRegexValidation;

            string nameValidation = GetLocalResourceObject("rfvalNameText").ToString();
            rfvalName.ToolTip = nameValidation;
            rfvalName.ErrorMessage = nameValidation;

            string AddressValidation = GetLocalResourceObject("rfvalAddressText").ToString();
            rfvalAddress.ToolTip = AddressValidation;
            rfvalAddress.ErrorMessage = AddressValidation;

            string emailValidation = GetLocalResourceObject("rfvalEmailText").ToString();
            rfvalEmail.ToolTip = emailValidation;
            rfvalEmail.ErrorMessage = emailValidation;

            string ZipValidation = GetLocalResourceObject("rfvalZipCodeText").ToString();
            rfvalZipCode.ToolTip = ZipValidation;
            rfvalZipCode.ErrorMessage = ZipValidation;

            string CityValidation = GetLocalResourceObject("rfvalCityText").ToString();
            rfvalCity.ToolTip = CityValidation;
            rfvalCity.ErrorMessage = CityValidation;

            valSumAdminEditDepartment.HeaderText = GetLocalResourceObject("valSumAdminEditDepartmentText").ToString();
        }

        protected void btnCancelEditDepartment_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Admin/adminDepartment.aspx");
        }
    }
}